package com.lzh.others.basejava.Thread_21;

import java.util.concurrent.*;

/**
 * @Description: FutureTask使用场景：
 * 多个事情可以并行，但是结果需要统一返回
 * @Author: LiuZiHao
 * @Date: 2022/12/28 14:57
 */
public class FutureTaskLearn {
    public static void main(String[] args) {
        Callable<String> callable = () -> {
            System.out.println("我是子任务");
            return "sub task done";
        };
        FutureTask<String> task = new FutureTask<>(callable);
        Thread thread = new Thread(task);
        thread.start();
        System.out.println("子线程启动");
        try {
            //调用get()方法 主线程不停向该线程发起请求，询问子线程的返回结果
//            String subResult = task.get();
            String subResult = task.get(5, TimeUnit.SECONDS);
            System.out.println("子线程返回值 = " + subResult);
        } catch (InterruptedException | ExecutionException e) {
            Throwable cause = e.getCause();
            e.printStackTrace();
        } catch (TimeoutException e) {
            //超时后处理流程
        }
        System.out.println("main结束");
    }
}
